const curl = require('./curl');
const xlsx = require('./xlsx');
const moment = require('moment');

const get_world_data = function () {
  const url = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5";

  return new Promise(function (resolve, reject) {
    curl.download(url, function (res) {
      if (res) {
        let res_json = JSON.parse(res);
        let data_json = JSON.parse(res_json.data);

        let world_data_list = data_json.areaTree;
        let china_day_list = data_json.chinaDayList;
        let china_dayadd_list = data_json.chinaDayAddList;

        console.log('获取QQ数据成功！');

        let data_array = [world_data_list, china_day_list, china_dayadd_list];
        resolve(data_array);
      } else {
        reject('获取QQ数据失败！')
      }
    })
  });
}

const get_children = function (parent, items) {
  if (parent['children']) {
    let children = parent['children'];
    children.forEach(ele => {
      items.push([
        ele.name, ele.today.confirm, ele.today.suspect, ele.today.dead, ele.today.heal, ele.today.isUpdated,
        ele.total.confirm, ele.total.suspect, ele.total.dead, ele.total.heal
      ]);

      get_children(ele, items);
    });
  }
}

const get_data = async function (file) {
  let world_data = await get_world_data();

  let world_data_list = world_data[0];
  let china_day_list = world_data[1];
  let china_dayadd_list = world_data[2];

  const headers = ['地区',
    '今日确诊', '今日疑似', '今日死亡', '今日治愈', '是否更新',
    '确诊合计', '疑似合计', '死亡合计', '治愈合计'
  ];

  // 解析全球数据
  let world_data_array = [headers];

  world_data_list.forEach(ele => {
    world_data_array.push([
      ele.name, ele.today.confirm, ele.today.suspect, ele.today.dead, ele.today.heal, ele.today.isUpdated,
      ele.total.confirm, ele.total.suspect, ele.total.dead, ele.total.heal
    ])
  });

  // 解析中国数据
  let china_data_array = [headers];
  get_children(world_data_list[0], china_data_array);

  // 解析中国每日数据
  let china_day_array = [
    ['日期', '确诊', '疑似', '死亡', '治愈', '死亡率', '治愈率']
  ];
  china_day_list.forEach(ele => {
    china_day_array.push([
      ele.date, ele.confirm, ele.suspect, ele.heal, ele.deadRate, ele.healRate
    ]);
  });

  // 解析中国每日变化数据
  let china_dayadd_array = [
    ['日期', '确诊', '疑似', '死亡', '治愈', '死亡率', '治愈率']
  ];
  china_dayadd_list.forEach(ele => {
    china_dayadd_array.push([
      ele.date, ele.confirm, ele.suspect, ele.heal, ele.deadRate, ele.healRate
    ]);
  });

  let new_file = new xlsx.Xlsx(file);

  new_file.add({
    name: '全球',
    data: world_data_array
  });

  new_file.add({
    name: '中国',
    data: china_data_array
  });

  new_file.add({
    name: '全国每日趋势',
    data: china_day_array
  });

  new_file.add({
    name: '全国每日变化',
    data: china_dayadd_array
  });

  await new_file.writeFileSync();
}

exports.get_data = get_data;